import {Component, EventEmitter, Inject, Input, OnInit, Output} from '@angular/core';
import {easeOut} from 'ol/easing';
import OlView from 'ol/View';
import {BaseComponent} from '../../entity/base-component';
import {BaseMapComponent} from '../../base-map/base-map.component';

@Component({
    selector: 'sb-map-zoom',
    templateUrl: './map-zoom.component.html',
    styleUrls: ['./map-zoom.component.less']
})
export class MapZoomComponent implements OnInit, BaseComponent {

    @Output()
    closeEvent = new EventEmitter<any>();
    private view: OlView;
    private duration_ = 250;

    constructor(@Inject(BaseMapComponent) public readonly baseMap: BaseMapComponent) {
    }

    @Input()
    set duration(duration_: number) {
        this.duration_ = duration_;
    }

    triggerClose() {
        this.closeEvent.emit();
    }


    ngOnInit() {
        this.view = this.baseMap.map.view;
    }

    zoomIn() {
        this.zoom(1);
    }

    zoomOut() {
        this.zoom(-1);
    }

    private zoom(delta: number = 1) {
        const view = this.view;
        const currentZoom = Math.round(view.getZoom());
        const currentResolution = view.getResolution();
        if (currentZoom) {
            const newResolution = view.getResolutionForZoom(currentZoom + delta);
            if (newResolution !== currentResolution) {

                if (this.duration_ > 0) {
                    if (view.getAnimating()) {
                        view.cancelAnimations();
                    }
                    view.animate({
                        resolution: newResolution,
                        duration: this.duration_,
                        easing: easeOut
                    });
                } else {
                    view.setResolution(newResolution);
                }
            }
        }
    }
}
